package com.dc.wifi.main.ui.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import com.dc.netlib.base.BaseFragment
import com.dc.wifi.BR
import com.dc.wifi.R
import com.dc.wifi.databinding.FragmentHomeBinding
import com.dc.wifi.main.Commons.Constant
import com.dc.wifi.main.DCApplication
import com.dc.wifi.main.model.HomeViewModel
import com.dc.wifi.main.ui.activity.DevicesActivity
import com.dc.wifi.main.ui.activity.LoginActivity
import com.dc.wifi.main.ui.activity.MainActivity
import com.dc.wifi.main.ui.dialog.CustomDialog
import com.dc.wifi.main.utils.ContinuousAPScanner
import com.dc.wifi.main.utils.WifiScannerUtil
import com.qmuiteam.qmui.skin.QMUISkinManager


/**
 *Author: chinadragon
 *Time: 2024/5/25
 */
class HomeFragment :
    BaseFragment<HomeViewModel, FragmentHomeBinding>(R.layout.fragment_home, BR.mHomeViewModel) {
    companion
    object {
        fun createFragment(bundle: Bundle = Bundle()): HomeFragment {
            return HomeFragment().apply {
                arguments = bundle
            }
        }
    }

    override fun initData() {
        super.initData()
        binding.switchWifi.setOnCheckedChangeListener { _, isChecked ->

            if (isChecked) {

                QMUISkinManager.defaultInstance(context).changeSkin(Constant.SKIN_1)

            } else {
                QMUISkinManager.defaultInstance(context).changeSkin(Constant.SKIN_2)

            }
        }
        binding.btnScan.setOnClickListener { view ->
            Toast.makeText(context, "scan", Toast.LENGTH_SHORT).show()
                yyy()
        }
        val screenSizeInPixels = getScreenSizeInPixels(DCApplication.getInstance())
        val screenDensity = getScreenDensity(DCApplication.getInstance())
        val sizeInPixels = convertDpToPixels(context, 750, 1624)

        println("Current screen size in pixels: ${screenSizeInPixels.x}x${screenSizeInPixels.y}")
        println("Current screen density: $screenDensity")
        println("750x1624dp in pixels: ${sizeInPixels.x}x${sizeInPixels.y}")

        context?.let { getInfo(it) }

        binding.colNetworkAssurance.setOnClickListener {
            startActivity(Intent(activity,LoginActivity::class.java))
        }
    }

    private fun yyy(): Unit {

        val scanner = ContinuousAPScanner(DCApplication.getInstance())
        scanner.setOnScanResultsListener { results ->
            // 处理扫描结果
            for (result in results) {
                val ssid = result.SSID
                val bssid = result.BSSID

                val signalStrength = result.level
//                    Log.d("lufei",result.toString())
                // 处理每个 AP 的信息
                Log.d("lufei", "ssid: $ssid, bssid: $bssid, signalStrength: $signalStrength")
//                    if (result.capabilities.contains("WEP")) {
//                        // WiFi加密方式为WEP
//                        Log.d("WiFi Encryption", "WEP");
//                    } else if (result.capabilities.contains("WPA") || result.capabilities.contains("WPA2")) {
//                        // WiFi加密方式为WPA或WPA2
//                        Log.d("WiFi Encryption", "WPA/WPA2");
//                    } else {
//                        // 未加密
//                        Log.d("WiFi Encryption", "Open");
//                    }
            }
            Log.d("lufei长度", results.size.toString())
//            scanner.stopContinuousScanning()
        }
        scanner.startContinuousScanning();

    }

    private fun xxx(): Unit {
//            val wifiManager = getSystemService(DCApplication.getInstance(), WifiManager::class.java)
        val wifiScannerUtil =
            WifiScannerUtil(DCApplication.getInstance()) // 'this' 是当前的Activity或Service的上下文
        try {
            val wifiNetworksJson = wifiScannerUtil.scanWifiNetworks()
            // 使用wifiNetworksJson，例如显示在UI上或进行其他处理
//                Log.d("lufei", "wifiNetworksJson: $wifiNetworksJson")
            for (c in wifiNetworksJson) {
                Log.d("lufei", "c: $c" + "\n" + c.BSSID)
            }
        } catch (e: SecurityException) {
            // 处理权限问题
            e.printStackTrace()
        } catch (e: IllegalStateException) {
            // 确保scanWifiNetworks是在主线程调用的
            e.printStackTrace()
        }
    }

    private fun ccc(): Unit {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val connectivityManager =
                DCApplication.getInstance()!!
                    .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val builder = NetworkRequest.Builder()
            builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            connectivityManager.registerNetworkCallback(
                builder.build(),
                object : NetworkCallback() {
                    override fun onAvailable(network: Network) {
                        super.onAvailable(network)
                        val wifiManager =
                            context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                        val wifiInfo = wifiManager.connectionInfo
                        val bssid = wifiInfo.bssid
                        // 使用 bssid
                        Log.d("lufei", "bssid: ${wifiInfo.bssid}")
                    }
                })
        }
    }
    fun getScreenSizeInPixels(context: Context): Point {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        return size
    }

    fun getScreenDensity(context: Context): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        return metrics.densityDpi
    }
    fun convertDpToPixels(context: Context?, dpWidth: Int, dpHeight: Int): Point {
        val density = getScreenDensity(context!!)
        return Point(dpWidth * (density / 160), dpHeight * (density / 160))
    }
    fun showPop(info:WifiInfo): Unit {
        val customDialog = CustomDialog(requireContext(), R.style.center_privacy_policy_dialog)
        customDialog.loadData(info)
        customDialog.show()
    }

    var wifi: WifiManager? = null
  private  lateinit  var   info:WifiInfo
    private fun getInfo(context: Context) {
        wifi =context. getSystemService(Context.WIFI_SERVICE) as WifiManager
        info= wifi!!.getConnectionInfo()

        val maxText = info.macAddress
        val ipText: String = intToIp(info.ipAddress)
        var status = ""
        if (wifi!!.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            status = "WIFI_STATE_ENABLED"
        }
        val ssid = info.ssid
        val networkID = info.networkId
        val speed = info.linkSpeed
        val bssid = info.bssid
        val rssi = info.rssi
        val frequency = info.frequency
        val linkSpeed = info.linkSpeed
        binding.card1Tv1.text=ssid
        binding.card1Tv2.text= "连接到:$bssid"
    }
    private fun intToIp(ip: Int): String {
        return ((ip and 0xFF).toString() + "." + ((ip shr 8) and 0xFF) + "." + ((ip shr 16) and 0xFF) + "."
                + ((ip shr 24) and 0xFF))
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding.homeCard.setOnClickListener {
            showPop(info)
        }
        binding.homeBtn1.setOnClickListener {
            //DevicesActivity
            startActivity(Intent(activity, DevicesActivity::class.java))


        }
    }

    override fun onResume() {
        super.onResume()
        Toast.makeText(context,"请点击设备扫描",Toast.LENGTH_SHORT).show()
    }

}